package com.team3.ecommerce.controller;


import com.team3.ecommerce.domain.UserAuth;
import com.team3.ecommerce.domain.UserInfo;
import com.team3.ecommerce.service.UserAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class UserAuthController {
    @Autowired
    private UserAuthService userAuthService;


    @PostMapping("/user/register/checkPhone")//用于注册时ajax验证是否重复
    @ResponseBody
    public String checkPhone(@ModelAttribute("phonenumber") String phonenumber){
        if(userAuthService.checkDupPhone(phonenumber))
            return "false";
        else
            return "true";
    }

    @GetMapping("/user/register")
    public String userAuthRegPage(){
        return "userReg.html";
    }

    @PostMapping("/user/register")
    public String userAuthReg(UserAuth userAuth, UserInfo userInfo,String birthdate2) throws ParseException {
        if(birthdate2!=null){
            DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
            Date date = fmt.parse(birthdate2);
            userInfo.setBirthdate(date);
        }
        userAuthService.userReg(userAuth,userInfo);
        return "redirect:/index";
    }



    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); //Trim form values.
    }
}
